<?php

class WorkerService
{


    /*
     * 通过 mobile 得到 user
     *
     */

    public static function getWorkerByMobile($mobile)
    {
        $worker  = Worker::model()->find("mobile=:mobile ",
            array(":mobile" => $mobile));

        return $worker;


    }

    /*
     *
     * 增加工人
     */
    public static function addWorker($mobile,$password)
    {
        $worker  = new Worker();
        $worker->mobile = $mobile;
        $worker->password = $password;
        $worker->real_name = "";
        $worker->gender = "";
        $worker->avatar = "";
        $worker->born_year = "";

        $worker->create_time =  DateUtil::getNowTime();
        $worker->update_time = DateUtil::getNowTime();
        $worker->is_delete = 0;

        $r1= $worker->save();

        if (!$r1) {

             print_r($worker->errors);

            throw new Exception("工人注册失败".$worker->errors[0]);
        }


    }


    /*
     * 通过worker_id 获取 worker
     *
     */
    public static function getWorkerByWorker_id($worker_id)
    {
        $worker = Worker::model()->findByPK($worker_id);

        if(empty($worker))
            Util::OutputSimpleInJsonFormat(1,"工人不存在");

        return $worker;

    }

    /*
     * 模糊 用户数据
     *
     */
    public static function formatWorker($worker)
    {
        $worker->password = "";

        //服务内容

        return $worker;
    }

    /*
     * 模糊 用户身份证号
     *
     */
    public static function formatidcard($worker)
    {
        $string = $worker->idcard;

        //idcard 不存在
        if($string == null)
        {
            $worker->idcard = "";

            return $worker;
        }


        if(strlen($string)<=14)
        {
            return $worker;
        }




        for($i=6;$i<=14;$i++){
            $string[$i] = '*';
        }
        $worker->idcard = $string;

        //服务内容

        return $worker;
    }





    /*
     *
     * 修改密码
     */
    public static function changeUserPassword($password,$worker)
    {
        $worker->password = $password;
        $worker->update_time = DateUtil::GetCurrentUTCDateTime();

        $r1= $worker->save();

        if (!$r1) {

            //print_r($worker->errors);

            throw new Exception("修改密码错误");
        }


    }

    /*
     *
     * 修改工人信息
     */
    public static function changeWorkerInfo($worker_id,$price)
    {
        $worker = Worker::model()->findByPK($worker_id);

        Util::checkExistAndNotDelete($worker);

        $worker->price = $price;

        Util::updateObjData($worker);

        Util::saveObjData($worker);

        return $worker;


    }

    /*
     * 判断密码是否合法化
     *
     */
    public static function islegalPasswod($password)
    {

        //英文、数字6-20位字符
        $preg='/^[a-zA-Z\d_]{6,20}$/';

        if(preg_match($preg,$password)==false)
        {
            throw new Exception("密码不合法");
        }

    }

    /*
     * 判断密码是否合法化
     *
     */
    public static function islegalWorkerPasswod($password)
    {

        //英文、数字6-20位字符
        $preg='/^[a-zA-Z\d_]{32}$/';

        if(preg_match($preg,$password)==false)
        {
            throw new Exception("密码不合法");
        }

    }

    /*
     * 判断身份证是否合法化
     *
     */
    public static function islegalIDCard($id_card)
    {
        $flag = true;

        if(strlen($id_card) == 18)
        {
            $flag= WorkerService::idcard_checksum18($id_card);
        }
        elseif((strlen($id_card) == 15))
        {
            $id_card = WorkerService::idcard_15to18($id_card);
            $flag= WorkerService::idcard_checksum18($id_card);
        }
        else
        {
            $flag= false;
        }

        if($flag==false)
            throw new Exception("身份证格式不对");



    }

    // 计算身份证校验码，根据国家标准GB 11643-1999
    public static function idcard_verify_number($idcard_base)
    {
        if(strlen($idcard_base) != 17)
        {
            return false;
        }
        //加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        //校验码对应值
        $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        $checksum = 0;
        for ($i = 0; $i < strlen($idcard_base); $i++)
        {
            $checksum += substr($idcard_base, $i, 1) * $factor[$i];
        }
        $mod = $checksum % 11;
        $verify_number = $verify_number_list[$mod];
        return $verify_number;
    }
    // 将15位身份证升级到18位
    public static function idcard_15to18($idcard){
        if (strlen($idcard) != 15){
            return false;
        }else{
            // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
            if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false){
                $idcard = substr($idcard, 0, 6) . '18'. substr($idcard, 6, 9);
            }else{
                $idcard = substr($idcard, 0, 6) . '19'. substr($idcard, 6, 9);
            }
        }
        $idcard = $idcard . WorkerService::idcard_verify_number($idcard);
        return $idcard;
    }
    // 18位身份证校验码有效性检查
    public static function idcard_checksum18($idcard){
        if (strlen($idcard) != 18){ return false; }
        $idcard_base = substr($idcard, 0, 17);
        if (WorkerService::idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))){
            return false;
        }else{
            return true;
        }
    }

    /*
     * 判断旧密码是否和数据库一致
     *
     */
    public static function isSamePasswod($oldPassword,$user)
    {
        if ($user->password != $oldPassword)//用户旧密码错误
        {
            throw new Exception("用户旧密码错误");
        }


    }
    /*
         * 修改用户信息
         *
         */
    public static function changeUserInfo($user,$real_name,$deviceInfo,$user_head,$sex)
    {


        $user->sex = $sex;
        $user->real_name = $real_name;
        $user->deviceInfo = $deviceInfo;
        $user->user_head = $user_head;
        $user->update_time =  DateUtil::GetCurrentUTCDateTime();



        $r1= $user->save();

        if (!$r1) {

            print_r($user->errors);

            throw new Exception("input into user error");
        }

    }

    /*
     *
     * 手机号验证
     *
     */
    public  static function isVaildMobile($mobile)
    {


        //手机号
        $preg="/^1[34578]\d{9}$/";

        if(preg_match($preg,$mobile)==false)
        {
            throw new Exception("手机号不合法");
        }



    }

    /*
     * 登录
     * cxj
     */
    public static function login($mobile,$pwd)
    {
        $worker = Worker::model()->find("mobile=:mobile",
            array(":mobile" => $mobile));

        //手机号是否存在
        if(empty($worker))
        {
            throw new Exception("手机号不存在");
        }
        //密码是否正确
        if(strtolower($worker->password)== strtolower($pwd))
        {
            return $worker;
        }
        else
            throw new Exception("密码错误");


    }

    /*
     * 手机验证码 登录
     * cxj
     */
    public static function smsLogin($mobile,$msg_code)
    {
        $worker = Worker::model()->find("mobile=:mobile",
            array(":mobile" => $mobile));

        //手机号是否存在
        if(empty($worker))
        {
            throw new Exception("手机号不存在");
        }

        //验证码是否正确
        SmsService::isVaildCode($mobile,$msg_code,MsgConst::SMS_TYPE_LOGIN_WORKER);

        return $worker;


    }

    /*
     * 提交认证
     */
    public static function addNewVeirfy($worker,$avatar,$id_card,$pic_idcard,$real_name,$type_id,$work_year,$price)
    {

        $connection=Yii::app()->db;

        $transaction=$connection->beginTransaction();//事物开始


        try
        {
            //修改工人提交状态
            WorkerService::changeWorkerVerifyStatus($worker,MsgConst::WORKER_VERIFY_STATUS_SUBMITING);

            Util::log_outptut("修改工人提交状态");
            //写入请求
            WorkerVerifyRequestService::addNewRequest($worker,$avatar,$id_card,$pic_idcard,$real_name,$type_id,$work_year,$price,MsgConst::WORKER_VERIFY_STATUS_SUBMITING);





            $transaction->commit();//事物结束
        }catch (Exception $e)
        {
            $transaction->rollback();//回滚函数

            throw new Exception($e->getMessage());

        }

    }

    /*
     * 修改工人的审核状态
     *
     */
    public static function changeWorkerVerifyStatus($worker,$status)
    {
        $worker->is_verify = $status;
        Util::updateObjData($worker);
        Util::saveObjData($worker);

    }

    public static function updatWorkerByReuqest($worker,$request)
    {
        $worker->real_name = $request->real_name;
        $worker->avatar = $request->avatar;
        $worker->idcard = $request->id_card;
        $worker->pic_idcard = $request->pic_idcard;
        $worker->type_name = $request->type_name;
        $worker->type_id = $request->type_id;
        $worker->work_year = $request->work_year;

        $worker->worker_num = WorkerService::getWokerNumByWorkerid($worker);

        $worker->price = $request->price;

        $worker->gender =   ((int)substr($worker->idcard,strlen($worker->idcard)-2,1))%2;


    }

    public static function getWokerNumByWorkerid($worker)
    {
        $str =  "0".$worker->type_id.MsgConst::WORKER_NUM_YEAR;

        $l = 4;

        $strid = "".$worker->worker_id;

        $str_l = strlen($strid);

        for($i=0;$i<($l-$str_l);$i++)
            $str = $str."0";

        $str = $str.$worker->worker_id;

        return $str;



    }



    /*
     * 同意审核
     *
     */
    public static function acceptRequest($request,$worker,$reason)
    {

        if($request->status != MsgConst::WORKER_VERIFY_STATUS_SUBMITING)
            throw new Exception("该申请已被处理");



        $connection=Yii::app()->db;

        $transaction=$connection->beginTransaction();//事物开始

        try
        {

            //更新工人状态
            WorkerService::updatWorkerByReuqest($worker,$request);

            //修改工人提交状态
            WorkerService::changeWorkerVerifyStatus($worker,MsgConst::WORKER_VERIFY_STATUS_VERIFIED);

            //修改申请状态
            WorkerVerifyRequestService::changeRequestStatus($request,MsgConst::WORKER_VERIFY_STATUS_VERIFIED,$reason);




            $transaction->commit();//事物结束
        }catch (Exception $e)
        {
            $transaction->rollback();//回滚函数

            throw new Exception($e->getMessage());

        }


    }

    /*
     * 拒绝审核
     *
     */
    public static function denyRequest($request,$worker,$reason)
    {

        if($request->status != MsgConst::WORKER_VERIFY_STATUS_SUBMITING)
            throw new Exception("该申请已被处理");



        $connection=Yii::app()->db;

        $transaction=$connection->beginTransaction();//事物开始

        try
        {



            $worker->reason = $reason;

            //修改工人提交状态
            WorkerService::changeWorkerVerifyStatus($worker,MsgConst::WORKER_VERIFY_STATUS_DENIED);

            //修改申请状态
            WorkerVerifyRequestService::changeRequestStatus($request,MsgConst::WORKER_VERIFY_STATUS_DENIED,$reason);




            $transaction->commit();//事物结束
        }catch (Exception $e)
        {
            $transaction->rollback();//回滚函数

            throw new Exception($e->getMessage());

        }


    }

    /*
    * 工人签到
    *
    */
    public static function checkin($worker_id)
    {
        $worker = Worker::model()->findByPK($worker_id);
        Util::checkExistAndNotDelete($worker);

        //判断今天是否已经签到
        $last_checkin_date = $worker->check_in_day;

        if($last_checkin_date != null)
        {

            $checkinday = substr($last_checkin_date,0,10);
            $today =  substr(DateUtil::getNowTime(),0,10);

            Util::log_outptut("today ".$today.$checkinday);


            if((string)$today == (string)$checkinday)
                throw new Exception("您今天已经签到");

        }

        //签到操作


        //事务开始
        $connection = Yii::app()->db;

        $transaction = $connection->beginTransaction();

        try {

            //增加工人的签到
            $worker->check_in_count +=1;
            $worker->check_in_day = DateUtil::getNowTime();
            Util::updateObjData($worker);
            Util::saveObjData($worker);

            //新增签到记录
            $checkinlog = new WorkerCheckin();
            $checkinlog->worker_id = $worker_id;
            Util::initObjData($checkinlog);
            Util::saveObjData($checkinlog);



            $transaction->commit();//事务结束
        } catch (Exception $e) {
            $transaction->rollback();//回滚函数

            throw new Exception($e->getMessage());

        }








    }

    //获取排序方式
    /*
    *
    *
    */
    public static function getOrderStr($searchsql,$sort_type)
    {
        $orderstr ="";
        //默认排序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_DEFAULT)
        {
            $orderstr = "";

        }

        //评分倒序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_RATING_DESC)
        {
            $orderstr = " order by rating_avg desc ";

        }


        //评分升序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_RATING_ASC)
        {
            $orderstr = " order by rating_avg asc ";

        }


        //价格倒序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_PRICE_DESC)
        {
            $orderstr = " order by price desc ";

        }


        //价格升序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_PRICE_ASC)
        {
            $orderstr = " order by price asc ";

        }


        //距离倒序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_DIST_DESC)
        {
            $orderstr = " order by price desc ";

        }

        //距离升序
        if($sort_type == MsgConst::WORKER_SORT_TYPE_DIST_ASC)
        {
            $orderstr = " order by price asc ";

        }

        $searchsql = $searchsql." ".$orderstr;


        return $searchsql;





    }

    /**
     *求两个已知经纬度之间的距离,单位为千米
     *@param lng1,lng2 经度
     *@param lat1,lat2 纬度
     *@return float 距离，单位千米
     **/
    public static function calc_distance($lng1,$lat1,$lng2,$lat2)//根据经纬度计算距离
    {
        //将角度转为弧度
        $radLat1=deg2rad($lat1);
        $radLat2=deg2rad($lat2);
        $radLng1=deg2rad($lng1);
        $radLng2=deg2rad($lng2);
        $a=$radLat1-$radLat2;//两纬度之差,纬度<90
        $b=$radLng1-$radLng2;//两经度之差纬度<180
        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
        return $s;
    }




}


?>